package com.wp.admin.service.impl;

import com.wp.admin.mapper.SysUserTokenMapper;
import com.wp.admin.pojo.SysUserToken;
import com.wp.admin.service.SysUserTokenService;
import com.wp.common.utils.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author wp
 * @create 2019-03-03 15:48
 */
@Service
@Transactional
public class SysUserTokenServiceImpl implements SysUserTokenService {

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;

    // 12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public SysUserToken createToken(Long id) {
        // 生成一个token
        String token = TokenGenerator.generateToken();
        // 获取当前时间
        Date now = new Date();
        // 生成过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        // 判断是否已生成token
        SysUserToken sysUserToken = findByUserId(id);
        if (sysUserToken == null) {
            sysUserToken = new SysUserToken();
            sysUserToken.setUserId(id);
            sysUserToken.setToken(token);
            sysUserToken.setLastUpdateTime(now);
            sysUserToken.setExpireTime(expireTime);
            sysUserTokenMapper.insert(sysUserToken);
        } else {
            sysUserToken.setToken(token);
            sysUserToken.setLastUpdateTime(now);
            sysUserToken.setExpireTime(expireTime);
            sysUserTokenMapper.updateByPrimaryKeySelective(sysUserToken);
        }
        return sysUserToken;
    }

    @Override
    public SysUserToken findByToken(String token) {
        SysUserToken sysUserToken = new SysUserToken();
        sysUserToken.setToken(token);
        return sysUserTokenMapper.selectOne(sysUserToken);
    }

    private SysUserToken findByUserId(Long id) {
        SysUserToken sysUserToken = new SysUserToken();
        sysUserToken.setUserId(id);
        sysUserToken = sysUserTokenMapper.selectOne(sysUserToken);
        return sysUserToken;
    }
}
